<template>
  <div class="page-cart">
    <el-row>
      <el-col
        v-if="cart.length"
        :span="24"
        class="m-cart"
      >
        <list :cart-data="cart" class="cart-list" />
        <ul class="m-cart-list">
          <li v-for="(item, index) of cart" :key="index">
            <p class="name">
              项目：{{ item.name }}
            </p>
            <p class="price">
              单价：{{ item.price }}
            </p>
            <p class="count">
              数量：
              <el-input-number v-model="item.count" size="mini" :min="1" :max="10" label="数量" />
            </p>
          </li>
        </ul>
        <p>
          应付金额：<em class="money">￥{{ total }}</em>
        </p>
        <div class="post">
          <el-button
            type="primary"
            @click="submit"
          >
            提交订单
          </el-button>
        </div>
      </el-col>
      <el-col
        v-else
        class="empty"
      >
        购物车为空
      </el-col>
    </el-row>
  </div>
</template>

<script>
import List from '@/components/cart/list.vue'
export default {
  components: {
    List
  },
  data() {
    return {
      cart: []
    }
  },
  computed: {
    total() {
      let total = 0
      this.cart.forEach((item) => {
        total += item.price * item.count
      })
      return total
    }
  },
  async asyncData(ctx) {
    const { status, data: { code, data: { name, price } } } = await ctx.$axios.post('/cart/getCart', {
      id: ctx.query.id
    })
    if (status === 200 && code === 0 && name) {
      return {
        cart: [{
          name,
          price,
          count: 1
        }],
        cartNo: ctx.query.id
      }
    }
  },
  methods: {
    submit: async function () {
      const { status, data: { code, id } } = await this.$axios.post('/order/createOrder', {
        count: this.cart[0].count,
        price: this.cart[0].price,
        id: this.cartNo
      })
      if (status === 200 && code === 0) {
        this.$confirm(`<p style="padding-top: 30px">恭喜您，已成功下单，订单号:${id}</p>`, '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          showClose: false
        }).then(() => {
          this.$router.push('/order')
        })
          .catch((action) => {
            action === 'cancel' ? this.$router.go(-1) : this.$router.push('/order')
          })
      }
    }
  }

}
</script>

<style lang="scss">
  @import "@/assets/css/cart/index.scss";
</style>
